Python 计数器键() return 值

Python Counter keys() return values

我有一个已经按出现次数排序的计数器。

counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}).

但是当我执行 counterlist.keys() 时,return 列表是:

['wirespe', 'four', 'accus',...]

而不是

['they', 'would', 'your',...].

为什么?

Counter()

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

是一个无序的字典,所以它不会保持你将它们添加到字典中的顺序。如果你想让它们按顺序排列,你需要使用 OrderedDict()

如果你想要一个 OrderedCounter() 那么你可以这样做,我从 here 中提取了它,它解释了为什么它有效。

from collections import *

class OrderedCounter(Counter, OrderedDict):
    pass

counterlist = OrderedCounter({'would': 203, 'they': 138, 'your': 134})

print counterlist.keys()

当您以特定顺序在字典中输入值时,字典不会保留任何顺序。 .keys() 在字典上 return 没有特别的顺序。有一个 OrderedDict 确实保留顺序,但我不知道它如何与 Counter 交互。

编辑:

您可能想要使用 Counter.most_common()。这将 return 一个元组列表, 有序。

另一种不创建额外 class 的解决方案是获取您拥有的项目集并根据计数的键对它们进行排序。以下代码基于@user3005486:

import collections

#if this is your list    
list_to_be_sorted = ['they', 'would', 'they', ...]
#then counterlist = {'would': 203, 'they': 138, 'your': 134}
counterlist = collections.Counter(list_to_be_sorted)
#if you sort this list ascendingly you get ['would', 'would', ..., 'they', 'they', ...etc.]
sorted_words = sorted(counterlist, key: lambda x:-counterlist[x])
distinct_words_from_list = set(list_to_be_sorted)
sorted_distinct_list = sorted(distinct_words_from_list, key: lambda x:-counterlist[x])
#then sorted_distinct_list = ['would', 'they', 'your']

问题来自 2016 年,同时 Python 中的词典保证按照 PEP 468.

保留插入顺序

来自docs

Changed in version 3.7: As a dict subclass, Counter Inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand.

所以,对于 Python >= 3.7

counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...})
counterlist.keys()                                                                                                                                           
# Out: dict_keys(['they', 'would', 'your'])

另请参阅:词典是否在 Python 3.6+ 中排序?